04. Flask-CORS

CORS

Flask-CORS

Welcome to your first Flask extension! Flask-CORS is the extension for handling CORS and its installation and usage are very simple.

In the workspace below, you'll find the basic code for enabling Flask-CORS on a simple application. If you hover the mouse over the code that is underlined in green, you'll see there are short movie explanations you can play for each of them.

Using the explanations in the workspace, see if you can answer the quiz that follows it.

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: jupyter
  • Opened files (when workspace is loaded): n/a

QUIZ QUESTION: :

Match the line of code with the relevant kind of Flask-CORS implementation

ANSWER CHOICES:



Code

Flask-CORS behavior

Route Specific Usage

Basic Initialization

Resource Specific Usage

SOLUTION:

Code

Flask-CORS behavior

Route Specific Usage

Basic Initialization

Resource Specific Usage

In this next video, we'll walk through how to implement all of the above code in your local environment, and get a little more in-depth about how it works. For additional practice, you may want to follow along using your own code editor and terminal. There's also a text summary below the video for your reference.

FSND C2 L3 A06 Flask CORS Summary

Flask CORS Summary

For your reference, here is a summary of all the steps we took (and the code we used) in the video.

Installation

In order to install Flask-CORS simply run

pip3 install -U flask-cors

Initialization

Once Flask-CORS is installed, you simply import the CORS function and call it with your app instance as a parameter. This will intialize Flask-CORS will all default options.

from flask_cors import CORS

app = Flask(__name__, instance_relative_config=True)
CORS(app)

Resource-Specific Usage

There are multiple options you can use to specify your Flask-CORS behavior. One typical one is resources, which contains a dictionary whose keys are regular expressions and values are dictionary or kwargs

cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

Route-Specific Usage

If you need to enable CORS on a given route, like those non-simple requests, you can use @cross_origin() to enable it.

@app.route("/hello")
@cross_origin()
def get_greeting():
    return jsonify({'message':'Hello, World!'})